import re
from django.urls import resolve, Resolver404
from .models import SiteVisit, PageVisitCount

class VisitStatisticsMiddleware:
    """用于记录网站访问统计的中间件"""
    
    def __init__(self, get_response):
        self.get_response = get_response
        # 排除的路径
        self.exclude_paths = [
            r'^/admin/',
            r'^/static/',
            r'^/media/',
            r'^/favicon\.ico',
            r'^/__debug__/', # Django Debug Toolbar
        ]
    
    def __call__(self, request):
        # 获取响应
        response = self.get_response(request)
        
        # 处理请求完成后记录访问统计
        if self._should_count_visit(request):
            self._record_visit(request)
            
        return response
    
    def _should_count_visit(self, request):
        """判断是否应该记录此次访问"""
        path = request.path_info
        
        # 排除特定路径
        for exclude_path in self.exclude_paths:
            if re.match(exclude_path, path):
                return False
                
        # 排除非GET请求
        if request.method != 'GET':
            return False
            
        return True
    
    def _record_visit(self, request):
        """记录访问"""
        path = request.path_info
        
        # 记录访问详情
        SiteVisit.objects.create(
            page=path,
            ip_address=self._get_client_ip(request),
            user_agent=request.META.get('HTTP_USER_AGENT', ''),
            referrer=request.META.get('HTTP_REFERER', '')
        )
        
        # 更新网站总访问量
        PageVisitCount.increment_count('site', 0, 'global')
        
        # 尝试解析当前URL以识别访问的资源类型
        try:
            url_name = resolve(path).url_name
            view_kwargs = resolve(path).kwargs
            
            # 规则详情页
            if url_name == 'detail' and 'rules' in resolve(path).app_name:
                rule_id = view_kwargs.get('pk')
                if rule_id:
                    PageVisitCount.increment_count('rule', rule_id, path)
            
            # 文章详情页
            elif url_name == 'article_detail' and 'articles' in resolve(path).app_name:
                article_id = view_kwargs.get('pk')
                if article_id:
                    PageVisitCount.increment_count('article', article_id, path)
            
        except Resolver404:
            # URL无法解析，忽略
            pass
    
    def _get_client_ip(self, request):
        """获取客户端真实IP地址"""
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        return ip 